<?php

namespace App\Http\Controllers\Api;

use App\Models\Order;
use App\Services\WechatService;
use Illuminate\Http\Request;
use GuzzleHttp\Client;

class ExpressController extends BaseController
{
    protected $wechatService;
    public function __construct(WechatService $wechatService)
    {
        $this->wechatService = $wechatService;
    }

    public function getQuota()
    {
        return $this->wechatService->getQuota();
    }

    public function updatePrinter()
    {
        //$openid = 'oykEg5WGTi181uPuJUX5jT7jlvr4';
        $openid = 'oykEg5eLJKoqEIVgr_df9CWCo51A';
        $ret = $this->wechatService->updatePrinter($openid);
        //dd($ret);
        return $this->ok($ret);
    }

    public function getPrinter()
    {
        $ret = $this->wechatService->getPrinter();
        //dd($ret);
        return $this->ok($ret);
    }

    public function getPath()
    {
        //$openid = 'oykEg5WGTi181uPuJUX5jT7jlvr4';
        //$order_id = '20190408153848592790';
        //$waybill_id = '73111684232979';
        //$ret = $this->wechatService->getExpressPath($openid, $order_id, $waybill_id);
        //dd($ret);
        //$str = '{"openid": "OPENID", "delivery_id": "SF", "waybill_id": "12345678901234567890","path_item_num": 3, "path_item_list": [{"action_time": 1533052800, "action_type": 100001, "action_msg": "快递员已成功取件"}, {"action_time": 1533062800, "action_type": 200001, "action_msg": "快件已到达xxx集散中心，准备发往xxx"}, {"action_time": 1533072800, "action_type": 300001, "action_msg": "快递员已出发，联系电话xxxxxx"}]}';
        //$arr = json_decode($str,true);
        //print_r(end($arr['path_item_list']));
        //print_r($arr['path_item_list']);
    }


    public function inputOrder()
    {
        return view('input_order');
    }

    public function getOrder(Request $request)
    {
        $order_no = trim($request->get('order_no'));
        $order = Order::query()->where('no',$order_no)->first();

        $print_html = '';
        if(!empty($order) && !empty($order->express_waybill_id))
        {
            $openid     = $order->user_openid;
            $order_id   = $order->no;
            $waybill_id = $order->express_waybill_id;

            $ret = $this->wechatService->getOrder($order_id, $openid, $waybill_id);
            if(isset($ret['print_html']))
            {
                $print_html = base64_decode($ret['print_html']);
            }
        }

        return view('get_order',compact('print_html'));
    }

    public function cancelOrder()
    {
        $openid = 'oykEg5WGTi181uPuJUX5jT7jlvr4';
        $order_id = '20190409135943060628';
        $waybill_id = '73111725811503';
        $ret = $this->wechatService->cancelOrder($order_id, $openid, $waybill_id);
        dd($ret);
    }
}
